package com.youkeyi.ddy.cloud.application.system.doc.controller;

import com.youkeyi.ddy.cloud.common.api.application.system.doc.SystemDocCloudService;
import com.youkeyi.ddy.cloud.common.api.application.system.doc.dto.SystemDocCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.system.doc.dto.SystemDocListCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.system.doc.dto.SystemDocListItemCloudDto;
import com.youkeyi.ddy.cloud.common.api.application.system.doc.param.SystemDocDeleteCloudParam;
import com.youkeyi.ddy.cloud.common.api.application.system.doc.param.SystemDocListCloudParam;
import com.youkeyi.ddy.cloud.common.api.application.system.doc.param.SystemDocUploadCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.pub.annex.PublicAnnexCloudService;
import com.youkeyi.ddy.cloud.common.api.basic.pub.annex.dto.PublicAnnexListCloudDto;
import com.youkeyi.ddy.cloud.common.api.basic.pub.annex.param.PublicAnnexCreateCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.pub.annex.param.PublicAnnexDeleteCloudParam;
import com.youkeyi.ddy.cloud.common.api.basic.pub.annex.param.PublicAnnexQueryCloudParam;
import com.youkeyi.ddy.cloud.common.context.YoukeyiSystemContext;
import com.youkeyi.ddy.cloud.common.enums.ResponseCodeEnum;
import com.youkeyi.ddy.cloud.common.response.ResponseContent;
import com.youkeyi.ddy.cloud.common.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * SystemDocController
 *
 * @Author liuxiawang
 * @Date 2024/2/29 6:08 PM
 * @Location shenzhen.china
 */
@Slf4j
@Service
public class SystemDocController implements SystemDocCloudService {

    @Value("${system.doc.temp:/home/doc/}")
    private String tempFolder;

    @Autowired
    private PublicAnnexCloudService publicAnnexCloudService;

    @Override
    public SystemDocCloudDto upload(HttpServletRequest request) {
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        if (null != file) {
            SystemDocCloudDto vo = new SystemDocCloudDto();
            if (StringUtils.isNotBlank(tempFolder)) {
                boolean isUploadSuccess = false;
                String filePath = getTempFolderPath(file.getOriginalFilename());
                File dest = new File(filePath);
                try {
                    // file.transferTo(dest.getAbsoluteFile());
                    FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(dest.toPath()));
                    isUploadSuccess = true;
                } catch (IOException e) {
                    e.printStackTrace();
                    vo.setErrorMessage("上传文件失败");
                }
                if (isUploadSuccess) {
                    String pathBase = dest.getPath(); //  /home/doc/template/1710226651123-D4C8838580C06C2652D67C57D796B899-mgg.jpeg
                    pathBase = pathBase.replace("/home/doc", "https://doc.ddy.yoyejia.com"); // https://doc.ddy.yoyejia.com/template/1710226651123-D4C8838580C06C2652D67C57D796B899-mgg.jpeg

                    // 数据入库
                    PublicAnnexCreateCloudParam annexCreateCloudParam = new PublicAnnexCreateCloudParam();
                    annexCreateCloudParam.setCorpKey(YoukeyiSystemContext.getCorpPrimaryKey());
                    annexCreateCloudParam.setFileName(file.getOriginalFilename());
                    annexCreateCloudParam.setUrl(pathBase);
                    if (null != request.getParameterMap()) {
                        annexCreateCloudParam.setAnnexTypeKey(request.getParameter("annexTypeKey"));
                        annexCreateCloudParam.setCorrelationKey(request.getParameter("customerKey"));
                    }
                    annexCreateCloudParam.setCreateUserKey(YoukeyiSystemContext.getUserPrimaryKey());
                    annexCreateCloudParam.setCreateUserName(YoukeyiSystemContext.getUserName());
                    ResponseContent responseContent = publicAnnexCloudService.create(annexCreateCloudParam);

                    vo.setKey(responseContent.getKey());
                    vo.setFileName(file.getOriginalFilename());
                    vo.setUrl(pathBase);
                    vo.setSuccessMessage("上传成功");
                } else {
                    vo.setErrorMessage("上传文件失败");
                }
            } else {
                vo.setErrorMessage("保存上传文件失败");
            }
            return vo;
        }
        return new SystemDocCloudDto(Boolean.FALSE, "无上传文件");
    }

    /**
     * 获取上传后文件的存放路径
     */
    private String getTempFolderPath(String filename) {
        return String.format("%s%d-%s-%s", tempFolder + "template/", System.currentTimeMillis(), MD5Utils.md5Encrypt32Upper(filename), filename);
    }

    @Override
    public SystemDocListCloudDto list(SystemDocListCloudParam param) {
        SystemDocListCloudDto dto = new SystemDocListCloudDto();
        String corpKey = YoukeyiSystemContext.getCorpPrimaryKey();
        if (StringUtils.isBlank(corpKey)) {
            dto.setErrorMessage(ResponseCodeEnum.TOKEN_INVALID.getMessage());
            return dto;
        }
        if (null == param) {
            dto.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return dto;
        }

        PublicAnnexQueryCloudParam annexQueryCloudParam = new PublicAnnexQueryCloudParam();
        annexQueryCloudParam.setAnnexPrimaryKeys(param.getAnnexPrimaryKeys());
        PublicAnnexListCloudDto annexDtos = publicAnnexCloudService.query(annexQueryCloudParam);
        if (null != annexDtos && CollectionUtils.isNotEmpty(annexDtos.getRows())) {
            List<SystemDocListItemCloudDto> items = new ArrayList<>();
            annexDtos.getRows().forEach(annex -> {
                SystemDocListItemCloudDto item = new SystemDocListItemCloudDto();
                item.setAnnexPrimaryKey(annex.getAnnexPrimaryKey());
                item.setFileName(annex.getFileName());
                item.setUrl(annex.getUrl());
                item.setAnnexTypePrimaryKey(annex.getAnnexTypePrimaryKey());
                item.setAnnexTypeCode(annex.getAnnexTypeCode());
                item.setAnnexTypeName(annex.getAnnexTypeName());
                items.add(item);
            });
            dto.setRows(items);
            dto.setTotal(annexDtos.getTotal());
        }
        dto.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return dto;
    }

    @Override
    public ResponseContent delete(SystemDocDeleteCloudParam param) {
        ResponseContent rc = new ResponseContent();
        String corpKey = YoukeyiSystemContext.getCorpPrimaryKey();
        if (StringUtils.isBlank(corpKey)) {
            rc.setErrorMessage(ResponseCodeEnum.TOKEN_INVALID.getMessage());
            return rc;
        }
        if (null == param || CollectionUtils.isEmpty(param.getDocPrimaryKeys())) {
            rc.setErrorMessage(ResponseCodeEnum.PARAMETER_ILLEGAL.getMessage());
            return rc;
        }

        PublicAnnexQueryCloudParam annexQueryCloudParam = new PublicAnnexQueryCloudParam();
        annexQueryCloudParam.setAnnexPrimaryKeys(param.getDocPrimaryKeys());
        PublicAnnexListCloudDto annexDtos = publicAnnexCloudService.query(annexQueryCloudParam);
        if (null != annexDtos && CollectionUtils.isNotEmpty(annexDtos.getRows())) {
            annexDtos.getRows().forEach(annex -> {
                if (StringUtils.isNotBlank(annex.getUrl())) {
                    String pathBase = annex.getUrl().replace("https://doc.ddy.yoyejia.com", "/home/doc"); // https://doc.ddy.yoyejia.com/template/1710226651123-D4C8838580C06C2652D67C57D796B899-mgg.jpeg
                    try {
                        File fileToDelete = new File(pathBase);
                        if (fileToDelete.exists()) {
                            boolean isDeleted = fileToDelete.delete();
                            if (isDeleted) {
                                log.info("文件已成功删除！");

                                PublicAnnexDeleteCloudParam annexDeleteCloudParam = new PublicAnnexDeleteCloudParam();
                                annexDeleteCloudParam.setAnnexPrimaryKeys(Collections.singletonList(annex.getAnnexPrimaryKey()));
                                annexDeleteCloudParam.setUpdateUserKey(YoukeyiSystemContext.getUserPrimaryKey());
                                annexDeleteCloudParam.setUpdateUserName(YoukeyiSystemContext.getUserName());
                                publicAnnexCloudService.delete(annexDeleteCloudParam);
                            } else {
                                log.error("无法删除该文件。");
                            }
                        } else {
                            log.info("指定的文件不存在。");
                        }
                    } catch (Exception e) {
                        log.error("删除文件失败！", e);
                    }
                }
            });
        }
        rc.setSuccessMessage(ResponseCodeEnum.SUCCESS.getMessage());
        return rc;
    }
}
